<template>
    <el-form label-width="80px">
        <el-form-item label="SPU名称">
            <el-input placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
            <el-select placeholder="请选择" v-model="(spuForm.tmId as number)">
                <el-option v-for="tm in tmList" :key="tm.id" :label="tm.tmName" :value="tm.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" v-model="spuForm.description" rows="4" placeholder="SPU描述" clearable @change="">
            </el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuImageList as UploadUserFile[]" :action="`${baseUrl}/admin/product/upload`"
                list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
            <el-select v-model="tempSaleAttr" :placeholder="`还剩${unUsedSaleAttrList.length}个没选`">
                <el-option v-for="attr in unUsedSaleAttrList" :key="attr.id" :label="attr.name"
                    :value="`${attr.id}:${attr.name}`">{{ attr.name }}
                </el-option>
            </el-select>
            <el-button type="primary" @click="addSaleAttr">添加销售属性</el-button>

        </el-form-item>
        <el-form-item>
            <el-table :data="spuSaleAttrList" border stripe>
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column prop="saleAttrName" label="属性名"></el-table-column>
                <el-table-column label="属性名称列表">
                    <template v-slot="{ row }">
                        <!-- @close="handleClose(tag)" -->
                        <el-tag v-for="tag in row.spuSaleAttrValueList" :key="tag.id" class="mx-1" closable
                            :disable-transitions="false">
                            {{ tag.saleAttrValueName }}
                        </el-tag>
                        <!--  
                            v-if="inputVisible" ref="InputRef" v-model="inputValue"
                            @keyup.enter="handleInputConfirm" 
                         -->
                        <el-input ref="editEle" @blur="handleInputConfirm(row)" v-model="row.inputValue"
                            v-if="row.isEdit" class="ml-1 w-20" size="small" />
                        <!-- 
                            v-else class="button-new-tag ml-1" size="small" @click="showInput"
                         -->
                        <el-button v-else @click="changeToEdit(row)" size="small">
                            + 新增属性值
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ row, $index }">
                        <el-button @click="spuSaleAttrList.splice($index, 1)" type="danger" icon="ele-Delete"
                            size="default"></el-button>
                    </template>
                </el-table-column>
            </el-table>

        </el-form-item>
        <el-form-item>
            <el-button @click="save" type="primary">保存</el-button>
            <el-button @click="emit('setState', 2)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "SpuForm",
});
</script>

<script setup lang="ts">
import { computed, onMounted, ref, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { requestSaveSpuInfo, requestSpuImgList, requestSpuSaleAttrList, requestUpdateSpuInfo, type BaseSaleAttrListType, type SpuImageListType, type SpuInfoType, type SpuSaleAttrItemType, type SpuSaleAttrListType, type SpuSaleAttrValueListType } from '@/api/spu';
import { requestBaseSaleAttrList } from '@/api/spu'
import type { TmListType } from '@/api/trademark';
import { requestAllTmList } from '@/api/trademark'
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'

//1.接受props传值
const props = defineProps<{
    spuForm: SpuInfoType
}>()

//2.接收自定义事件
const emit = defineEmits<{
    (event: 'setState', state: number, row?: SpuInfoType): void
}>()


/* const fileList = ref<UploadUserFile[]>([
    {
        name: 'food.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    }
]) */
const baseUrl = import.meta.env.VITE_API_URL



const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}


//3.根据新增还是修改去请求当前form表单需要的数据(其中新增需要发送:1.品牌列表 2.说有销售属性列表, 修改需要发送:1.品牌列表 2.所有销售属性列表 3.当前spu图片列表 4.当前spu的属性列表)
//声明一些数据 保存品牌列表 所有销售属性列表 当前spu图片列表 当前spu的属性列表
const tmList = ref<TmListType[]>([])
const saleAttrList = ref<BaseSaleAttrListType>([])
const spuImageList = ref<SpuImageListType>([])
const spuSaleAttrList = ref<SpuSaleAttrListType>([])

const getAllUseData = async () => {
    if (!props.spuForm.id) {
        try {
            const re1 = await requestAllTmList()
            tmList.value = re1
            const re2 = await requestBaseSaleAttrList()
            saleAttrList.value = re2
        } catch (e) {
            ElMessage.error('品牌请求或属性列表请求失败')
        }
    } else {
        //修改逻辑,发送四个请求
        const promise1 = requestAllTmList()
        const promise2 = requestBaseSaleAttrList()
        const promise3 = requestSpuImgList(props.spuForm.id)
        const promise4 = requestSpuSaleAttrList(props.spuForm.id)

        try {
            const re = await Promise.all([
                promise1, promise2, promise3, promise4
            ])
            tmList.value = re[0]
            saleAttrList.value = re[1]
            spuImageList.value = re[2]
            spuSaleAttrList.value = re[3]

            //处理图片回填
            spuImageList.value.forEach(i => {
                i.name = i.imgName,
                    i.url = i.imgUrl

                //给spu的销售属性列表的每一项添加isEdit属性,代表当前内部的属性值是添加模式还是编辑模式
                spuSaleAttrList.value.forEach(it => {
                    //保存当前销售属性列表中的模式是否是编辑模式
                    it.isEdit = false
                    //保存输入框的内容
                    it.inputValue = ''
                })

            })
        } catch (error) {
            ElMessage.error('初始请求失败')
        }
    }
}

//初始化获取数据
onMounted(() => {
    getAllUseData()
});

//计算属性获得剩余销售属性列表
const unUsedSaleAttrList = computed(() => {
    return saleAttrList.value.filter(i1 => {
        return spuSaleAttrList.value.every(i2 => {
            return i2.baseSaleAttrId !== i1.id
        })
    })
})

//定义一个数据 手机用户临时选择的销售属性
const tempSaleAttr = ref('')

//添加销售属性值事件
const addSaleAttr = () => {
    const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(':')
    //我们要把数据插入到spuSaleAttrList,所有要拼接一个类似的数据格式才能插入
    const tempSpuSaleAttr = {
        baseSaleAttrId: +baseSaleAttrId,
        saleAttrName: saleAttrName,
        spuSaleAttrValueList: []
    }
    //插入数据到spuSaleAttrList
    spuSaleAttrList.value.push(tempSpuSaleAttr)

    //清空临时数据
    tempSaleAttr.value = ''
}

//保存当前所在编辑模式的表单元素
const editEle = ref()
//切换编辑模式的事件函数
const changeToEdit = (row: SpuSaleAttrItemType) => {
    //切换模式
    row.isEdit = true;
    //自动获取焦点
    nextTick(() => {
        editEle.value.focus()
    })
}

//编辑框失去焦点的事件回调函数
const handleInputConfirm = (row: SpuSaleAttrItemType) => {
    //获取当前输入的内容
    let inputValue = row.inputValue as string
    console.log(inputValue);

    //判断输入的内容是否为空
    if (!inputValue?.trim()) {
        row.isEdit = false
        ElMessage.error('添加的属性不能为空')
        return
    }

    //判断输入的内容和之前的内容有没有重复
    const isRepeat = row.spuSaleAttrValueList.some((it) => {
        return it.saleAttrValueName === inputValue
    })
    console.log(isRepeat);

    if (isRepeat) {
        ElMessage.error('输入的属性有重复')
        row.isEdit = false
        row.inputValue = ''
        return
    }

    //把值添加到列表
    //整理以下要添加到row的属性值列表中的数据
    const newSaleAttrValue = {
        //当前所在的销售属性，对应的销售属性id
        baseSaleAttrId: row.baseSaleAttrId,
        //当前销售属性的值
        saleAttrValueName: row.inputValue as string,
        //其他值都不需要，可以不填
    };

    row.spuSaleAttrValueList.push(newSaleAttrValue);

    //最后要清空并切换到按钮模式
    row.isEdit = false;
    row.inputValue = "";

}

//保存事件函数
const save = async () => {
    //整理spuImageList数据
    const newSpuImageList = spuImageList.value.map(item => {
        if (item.response) {
            return {
                imgUrl: item.response.data as string,
                imgName: item.name as string,
            }
        } else {
            return {
                imgName: item.imgName,
                imgUrl: item.imgUrl,
            };
        }
    })

    //整理SaleAttrvalueList数据,因为里边多了isEdit和inputValue
    spuSaleAttrList.value.forEach(item => {
        delete item.isEdit,
            delete item.inputValue
    })

    //把整理好的数据替换之前的数据
    props.spuForm.spuImageList = spuImageList.value
    props.spuForm.spuSaleAttrList = spuSaleAttrList.value

    // 提交数据
    try {
        if (props.spuForm.id) {
            //更新操作
            await requestUpdateSpuInfo(props.spuForm);
        } else {
            //新增操作
            await requestSaveSpuInfo(props.spuForm);
        }
    } catch (e) {
        ElMessage.error("新增或者更新数据失败");
    }

    //回到列表页
    emit('setState',2)
}
</script>